package com.puff.service.impl;

import com.puff.constant.MessageConstant;
import com.puff.constant.StatusConstant;
import com.puff.dto.AdminEditPasswordDTO;
import com.puff.dto.AdminLoginDTO;
import com.puff.entity.Admin;
import com.puff.entity.Employee;
import com.puff.exception.AccountLockedException;
import com.puff.exception.AccountNotFoundException;
import com.puff.exception.PasswordErrorException;
import com.puff.mapper.AdminMapper;
import com.puff.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
@Slf4j
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    /**
     * 平台管理员登录
     * @param adminLoginDTO
     * @return
     */
    public Admin login(AdminLoginDTO adminLoginDTO) {
        String username = adminLoginDTO.getUsername();
        String password = adminLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Admin admin = adminMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (admin == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //e10adc3949ba59abbe56e057f20f883e
        //将前端传过来的明文密码通过md5加密，转化为密文的形式与数据库密码进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(admin.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (admin.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return admin;
    }

    /**
     * 修改密码
     * @param adminEditPasswordDTO
     */
    public void editPassword(AdminEditPasswordDTO adminEditPasswordDTO) {
        String username = adminEditPasswordDTO.getUsername();
        String oldPassword = adminEditPasswordDTO.getOldPassword();
        String newPassword = adminEditPasswordDTO.getNewPassword();

        // 根据用户名查询数据库中的数据
        Admin admin = adminMapper.getByUsername(username);

        //密码比对
        //e10adc3949ba59abbe56e057f20f883e
        //将前端传过来的明文密码通过md5加密，转化为密文的形式与数据库密码进行比对
        oldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if (!oldPassword.equals(admin.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        Admin newAdmin = new Admin();
        BeanUtils.copyProperties(adminEditPasswordDTO,newAdmin);

        newPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        newAdmin.setPassword(newPassword);
        newAdmin.setId(admin.getId());
        adminMapper.update(newAdmin);
    }
}
